﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
/// <summary>
/// Author: toanvt
/// CreatedDate: 13/12/2011
/// Description: Inser, Update Chuyên mục tin tức
/// </summary>
public partial class Administrator_AdminNewsIU : System.Web.UI.Page
{
    private Int32 tinTucID = HangSo.DEFAULT_ID;
    private String message = "";
    private Int32 danhMucTinTucID = HangSo.DEFAULT_ID;

    private DataTable dtNewsCategorys = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            tinTucID = Int32.Parse(Request.QueryString["TinTucID"].ToString());
        }
        catch (Exception)
        {
            tinTucID = HangSo.DEFAULT_ID;
        }

        try
        {
            message = Request.QueryString["Message"].ToString();
        }
        catch (Exception ex)
        {
            message = "";
        }

        //hiển thị Message nếu có giá trị Message gửi sang từ màn hình nguồn
        this.lbMessage.Text = message;
        this.lbMessage.CssClass = "BlueCorlor";

        try
        {
            danhMucTinTucID = Int32.Parse(Request.QueryString["DanhMucTinTucID"].ToString());
        }
        catch (Exception)
        {
        }

        if (!Page.IsPostBack)
        {

            dtNewsCategorys = DanhMucTinTucProvider.GetDanhsachtintucForBackEnd().Tables[0];
            // tao danh muc tin tuc trong drop dow list
            CreateDDLCategory(0, 0);
            this.ddlDanhMucTinTuc.Items.Insert(0, new ListItem("----Danh mục tin tức----", "-1"));

            if (tinTucID == -1)
            {
                ViewState["action"] = HangSo.ACTION_ADD;

                this.ddlDanhMucTinTuc.SelectedValue = danhMucTinTucID.ToString();
            }
            else
            {
                TinTuc theTinTuc = TinTucProvider.GetTinTucByTinTucID(tinTucID);

                if (theTinTuc == null)
                    Response.Redirect("AdminNews.aspx");
                else
                {
                    txtTieuDeVN.Text = theTinTuc.TieuDeVN.ToString();
                    txtTieuDeOther.Text = theTinTuc.TieuDeOther.ToString();
                    fckNoiDungVN.Value = theTinTuc.NoiDungVN.ToString();
                    fckNoiDungOther.Value = theTinTuc.NoiDungOther.ToString();
                    fckTomTatVN.Value = theTinTuc.TomTatVN.ToString();
                    fckTomTatOther.Value = theTinTuc.TomTatOther.ToString();
                    txtSapXep.Text = theTinTuc.SapXep.ToString();
                    ddlDanhMucTinTuc.SelectedValue = theTinTuc.DanhMucTinTucID.ToString();
                    chkNoiBat.Checked = theTinTuc.NoiBat;
                    ckPublish.Checked = theTinTuc.Trangthai;
                    this.imgHinhAnh.ImageUrl = @"~\ImageDatas\News\" + theTinTuc.HinhAnhUrl.ToString();
                    this.imgIcon.ImageUrl = @"~\ImageDatas\News\" + theTinTuc.Icon.ToString();

                    //thiết lập Nhóm Danh Mục
                    DanhMucTinTuc theDanhMucTinTuc = DanhMucTinTucProvider.GetDanhMucTinTucByDanhMucID(theTinTuc.DanhMucTinTucID);
                    this.ddlDanhMucTinTuc.SelectedValue = theDanhMucTinTuc.DanhMucTinTucID.ToString();

                    //thiết lập các thông tin cơ bản cho việc update
                    ViewState["TinTucID"] = theTinTuc.TinTucID;
                    ViewState["action"] = HangSo.ACTION_UPDATE;
                    ViewState["HinhAnhUrl"] = theTinTuc.HinhAnhUrl.ToString();
                    ViewState["Icon"] = theTinTuc.Icon.ToString();

                }
            }


            //ẩn các Validation cho các control Other
            if (HangSo.USING_MULTIL_LANGUAGE == false)
            {
                rvTieuDeOther.Enabled = false;
            }
        }
    }

    /// <summary>
    /// Author : chiennv
    /// CreatedDate : 07/02/2012
    /// Description : tạo DropDownList bằng đệ quy
    /// </summary>
    /// <param name="ChuyenMucChaID"></param>
    private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
    {
        String preString = "";

        for (Int32 i = 0; i < level; ++i)
        {
            preString += "--";
        }

        DataRow[] drCategorysSub = dtNewsCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
        Int32 amountOfCategorySub = drCategorysSub.Count();

        //Điểm dừng đệ quy
        if (amountOfCategorySub == 0)
            return;

        for (Int32 i = 0; i < amountOfCategorySub; ++i)
        {
            Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucTinTucID"].ToString());

            ListItem li = new ListItem(preString + drCategorysSub[i]["TenDanhMucTinTucVN"].ToString(), drCategorysSub[i]["DanhMucTinTucID"].ToString());
            this.ddlDanhMucTinTuc.Items.Add(li);
            CreateDDLCategory(subCategoryID, level + 1);
        }
    }

    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 13/12/2011
    /// Description: Validate trạng thái dữ liệu nhập
    /// </summary>
    /// <returns>Trạng thái thỏa mãn hay không</returns>
    private Boolean ValidateData()
    {
        this.lbMessage.Text = "";
        this.lbMessage.CssClass = "";

        String message = "";
        Boolean isSuccess = true;
        String sExtendsion = HangSo.IMAGE_VALIDATION;

        if (this.ddlDanhMucTinTuc.SelectedValue == "-1")
        {
            message += "Chọn chuyên mục tin tức <br />";
            isSuccess = false;
        }

        if (this.fuHinhAnhUrl.HasFile && sExtendsion.IndexOf(Path.GetExtension(fuHinhAnhUrl.PostedFile.FileName)) < 0)
        {
            message += "Ảnh sản đại diện không đúng <br />";
            isSuccess = false;
        }

        if (!isSuccess)
        {
            lbMessage.Text = message;
        }

        return isSuccess;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        String action = ViewState["action"].ToString();
        Int32 tinTucIDOut = -1;

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            TinTuc theTinTuc = new TinTuc();
            theTinTuc.TieuDeVN = txtTieuDeVN.Text.Trim();
            theTinTuc.TieuDeOther = txtTieuDeOther.Text.Trim();
            theTinTuc.NoiDungVN = fckNoiDungVN.Value.ToString().Trim();
            theTinTuc.NoiDungOther = fckNoiDungOther.Value.ToString().Trim();
            theTinTuc.TomTatVN = fckTomTatVN.Value.ToString().Trim();
            theTinTuc.TomTatOther = fckTomTatOther.Value.ToString().Trim();
            theTinTuc.NguoiTao = HttpContext.Current.User.Identity.Name;
            theTinTuc.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            theTinTuc.NoiBat = chkNoiBat.Checked;
            theTinTuc.DanhMucTinTucID = Int32.Parse(ddlDanhMucTinTuc.SelectedValue);
            theTinTuc.Trangthai = ckPublish.Checked;

            DataSet theDanhMucTinTuc = DanhMucTinTucProvider.GetDanhMucTinTucsByNhomDanhMucID(theTinTuc.DanhMucTinTucID);

            if (theDanhMucTinTuc.Tables[0].Rows.Count > 1)
            {
                lbMessage.Text = "Không thể thêm tin tức vào chuyên mục cha";
                return;
            }

            if (this.fuHinhAnhUrl.HasFile)
            {
                String fileName = fuHinhAnhUrl.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                fuHinhAnhUrl.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//News//" + newFileName);
                theTinTuc.HinhAnhUrl =  newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.HinhAnhUrl = "noImage.gif";
                }
                else
                {
                    theTinTuc.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
            }

            if (this.fuIcon.HasFile)
            {
                String fileName = fuIcon.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                fuIcon.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//News//" + newFileName);
                theTinTuc.Icon = newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.Icon = "noImage.gif";
                }
                else
                {
                    theTinTuc.Icon = ViewState["Icon"].ToString();
                }
            }

            Boolean isHot = this.chkHot.Checked;

            if (action == HangSo.ACTION_ADD)
            {
                theTinTuc.TinTucID = -1;
                tinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, isHot, true);
            }
            else
            {
                theTinTuc.TinTucID = Int32.Parse(ViewState["TinTucID"].ToString());
                tinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, isHot, false);
            }

            Response.Redirect("AdminNews.aspx?DanhMucTinTucID" + danhMucTinTucID);
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("AdminNews.aspx?DanhMucTinTucID=" + danhMucTinTucID);
    }

    protected void btnapply_Click(object sender, EventArgs e)
    {
        String action = ViewState["action"].ToString();
        Int32 tinTucIDOut = -1;

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            TinTuc theTinTuc = new TinTuc();
            theTinTuc.TieuDeVN = txtTieuDeVN.Text.Trim();
            theTinTuc.TieuDeOther = txtTieuDeOther.Text.Trim();
            theTinTuc.NoiDungVN = fckNoiDungVN.Value.ToString().Trim();
            theTinTuc.NoiDungOther = fckNoiDungOther.Value.ToString().Trim();
            theTinTuc.TomTatVN = fckTomTatVN.Value.ToString().Trim();
            theTinTuc.TomTatOther = fckTomTatOther.Value.ToString().Trim();
            theTinTuc.NguoiTao = HttpContext.Current.User.Identity.Name;
            theTinTuc.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            theTinTuc.NoiBat = chkNoiBat.Checked;
            theTinTuc.Trangthai = ckPublish.Checked;
            theTinTuc.DanhMucTinTucID = Int32.Parse(ddlDanhMucTinTuc.SelectedValue);

            DataSet theDanhMucTinTuc = DanhMucTinTucProvider.GetDanhMucTinTucsByNhomDanhMucID(theTinTuc.DanhMucTinTucID);

            if (theDanhMucTinTuc.Tables[0].Rows.Count > 1)
            {
                lbMessage.Text = "Không thể thêm tin tức vào chuyên mục cha";
                return;
            }

            if (this.fuHinhAnhUrl.HasFile)
            {
                String fileName = fuHinhAnhUrl.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                fuHinhAnhUrl.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//News//" + newFileName);
                theTinTuc.HinhAnhUrl = newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.HinhAnhUrl = "noImage.gif";
                }
                else
                {
                    theTinTuc.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
            }

            if (this.fuIcon.HasFile)
            {
                String fileName = fuIcon.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                fuIcon.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//News//" + newFileName);
                theTinTuc.Icon = newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_ADD)
                {
                    theTinTuc.Icon = "noImage.gif";
                }
                else
                {
                    theTinTuc.Icon = ViewState["Icon"].ToString();
                }
            }

            Boolean isHot = this.chkHot.Checked;

            if (action == HangSo.ACTION_ADD)
            {
                theTinTuc.TinTucID = -1;
                tinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, isHot, true);
            }
            else
            {
                theTinTuc.TinTucID = Int32.Parse(ViewState["TinTucID"].ToString());
                tinTucIDOut = TinTucProvider.IUTinTucs(theTinTuc, isHot, false);
            }

            Response.Redirect("AdminNewsIU.aspx?TinTucID=" + tinTucIDOut.ToString() + "&Message=Lưu thành công");
        }
    }
}
